import 'dart:math';

import 'package:baseProjectFlutter/utils/app_extends.dart';

class Result<T> {
  final T? successValue;
  final ErrorInfo? error;

  Result._success(this.successValue) : error = null;

  Result._failure(this.error) : successValue = null;

  factory Result.success(T value) => Result._success(value);

  factory Result.failure(Object e, StackTrace s) => Result._failure(ErrorInfo(e, s));

  Result<T> onSuccess(void Function(T) onSuccess) {
    if (isSuccess()) {
      onSuccess(successValue!);
    }
    return this;
  }

  Result<T> onFailure(void Function(ErrorInfo) onFailure) {
    if (isFailure()) {
      onFailure(error!);
    }
    return this;
  }

  bool isSuccess() => error == null;

  bool isFailure() => error != null;

  T? getOrNull() => successValue;

  Object? errorOrNull() => error;
}

Result<R> runCatching<R>(R Function() block) {
  try {
    final result = block();
    return Result.success(result);
  } catch (e, stackTrace) {
    return Result.failure(e, stackTrace);
  }
}

class ErrorInfo {
  final Object? e;
  final StackTrace? stackTrace;

  ErrorInfo(this.e, this.stackTrace);

  @override
  String toString() {
    return 'ErrorInfo{e: $e, stackTrace: ${stackTrace?.getStackTracePrintInfo()}}';
  }

  void printStackTrace() {
    print("StackTrace:${stackTrace?.getStackTracePrintInfo()}");
    // LogUtils.e("${e} stackTrace : ${stackTrace?.getStackTracePrintInfo()}");
  }
}

extension StackTraceEx on StackTrace {
  String getStackTracePrintInfo() {
    final lines = toString().split('\n');
    for (final line in lines) {
      if (line.isNotEmpty) {
        final parts = line.split(':');
        if (parts.length >= 2) {
          final file = parts.getOrNull(0)?.trim();
          final lineNum = parts.getOrNull(1)?.trim();
          final column = parts.getOrNull(2)?.trim();
          final method = parts.getOrNull(3)?.trim();
          return 'File: $file, Line: $lineNum, ${column == null ? "" : "Column: $column"}, ${method == null ? "" : "Method: $method"}';
        }
      }
    }
    return "";
  }

  void printStackTrace() {
    print("StackTrace:$getStackTracePrintInfo()");
    // LogUtils.e(getStackTracePrintInfo());
  }
}

void main() {
  final result = runCatching(() {
    // 模拟一个可能抛出异常的操作
    if (true) {
      return "Operation successful";
    } else {
      throw Exception("Operation failed");
    }
  }).onSuccess((it) {}).onFailure((e) {}).getOrNull;
  print("Success: ${result}");
  Future.microtask(() {
    throw Exception("Error");
  }).catchError((e, s) {
    print("Error2222: $e   $s");
  });
  print("Error3333333333:");
  // if (result.isSuccess()) {
  //   print("Success: ${result.getOrNull}");
  // } else {
  //   print("Failure: ${result.errorOrNull}");
  // }
}
